package com.tanhua.dubbo.api.service;

import com.aliyunoss.template.OssTemplate;
import com.baiduface.template.BaiduFaceTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.exception.BusinessException;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.ExceptionResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private BaiduFaceTemplate baiduFaceTemplate;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }


    public void update(UserInfo userInfo){
        userInfoApi.update(userInfo);
    }

    public UserInfo findById(Long id){
        return userInfoApi.findById(id);
    }

    public void updateHead(Long id, MultipartFile headPhoto) throws Exception{
        //1 将图片上传到阿里云
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2 调用百度云人脸检测工具检测人脸
        JSONObject jsonObject = baiduFaceTemplate.detectImg(url);
        // error_code = 0的时候是成功
        Integer error_code = (Integer) jsonObject.get("error_code");
        //3 检验通过，则更新数据库构想
        if (error_code!=0){
//            throw new RuntimeException("人脸检测失败");
            throw new BusinessException(ExceptionResult.faceError());
        }
        //包含人脸，更新数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);
    }
}
